<template>
  <div class="post-form-page">
    <a-page-header
      :title="isEditing ? '编辑帖子' : '新增帖子'"
      :sub-title="isEditing ? `编辑帖子 #${formData.id}` : '创建新的圈子帖子'"
      @back="handleBack"
    >
      <template #extra>
        <a-space>
          <a-button @click="handleSaveDraft">
            <SaveOutlined />
            保存草稿
          </a-button>
          <a-button @click="handleLoadDraft" v-if="hasDraft">
            <FileTextOutlined />
            加载草稿
          </a-button>
          <a-button @click="handleCancel">取消</a-button>
          <a-button type="primary" :loading="submitting" @click="handleSubmit">
            {{ isEditing ? '保存修改' : '发布帖子' }}
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <div class="page-content">
      <a-row :gutter="24">
        <!-- 左侧表单区域 -->
        <a-col :span="14">
          <a-card title="帖子信息" :bordered="false">
            <a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="帖子标题" name="title">
                    <a-input
                      v-model:value="formData.title"
                      placeholder="请输入帖子标题"
                      :maxlength="100"
                      show-count
                      @input="updatePreview"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="所属学校" name="schoolId">
                    <a-select
                      v-model:value="formData.schoolId"
                      placeholder="请选择学校"
                      show-search
                      allow-clear
                      :filter-option="false"
                      @search="handleSchoolSearch"
                      @change="updatePreview"
                    >
                      <a-select-option
                        v-for="school in schoolList"
                        :key="school.id"
                        :value="school.id"
                      >
                        {{ school.schoolName }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="帖子分类" name="categoryId">
                    <a-select
                      v-model:value="formData.categoryId"
                      placeholder="请选择分类"
                      allow-clear
                      @change="updatePreview"
                    >
                      <a-select-option
                        v-for="category in categoryList"
                        :key="category.id"
                        :value="category.id"
                      >
                        {{ category.categoryName }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="帖子状态" name="postStatus">
                    <a-select
                      v-model:value="formData.postStatus"
                      placeholder="请选择状态"
                      @change="updatePreview"
                    >
                      <a-select-option value="published">已发布</a-select-option>
                      <a-select-option value="pending">审核中</a-select-option>
                      <a-select-option value="hidden">已隐藏</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>

              <a-form-item label="帖子内容" name="content">
                <a-textarea
                  v-model:value="formData.content"
                  placeholder="请输入帖子内容"
                  :rows="8"
                  :maxlength="2000"
                  show-count
                  @input="updatePreview"
                />
              </a-form-item>

              <a-row :gutter="16">
                <a-col :span="8">
                  <a-form-item label="是否匿名" name="isAnonymous">
                    <a-radio-group v-model:value="formData.isAnonymous" @change="updatePreview">
                      <a-radio :value="0">实名</a-radio>
                      <a-radio :value="1">匿名</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="是否置顶" name="isPinned">
                    <a-switch
                      v-model:checked="formPinnedSwitch"
                      checked-children="置顶"
                      un-checked-children="普通"
                      @change="handlePinnedChange"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8" v-if="formData.isPinned === 1">
                  <a-form-item label="置顶过期时间" name="pinExpireTime">
                    <a-date-picker
                      v-model:value="formData.pinExpireTime"
                      show-time
                      placeholder="选择过期时间"
                      style="width: 100%"
                      :disabled-date="disabledDate"
                      @change="updatePreview"
                    />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-form-item label="话题标签">
                <a-select
                  v-model:value="formData.postTagList"
                  mode="tags"
                  placeholder="输入话题标签，按回车添加"
                  :max-tag-count="5"
                  style="width: 100%"
                  @change="updatePreview"
                >
                </a-select>
                <div class="form-tip">最多可添加5个话题标签</div>
              </a-form-item>

              <a-form-item label="帖子图片">
                <a-upload
                  v-model:file-list="uploadFileList"
                  list-type="picture-card"
                  :before-upload="beforeUpload"
                  :on-remove="onRemove"
                  accept="image/*"
                  multiple
                >
                  <div v-if="uploadFileList.length < 9">
                    <PlusOutlined />
                    <div style="margin-top: 8px">上传图片</div>
                  </div>
                </a-upload>
                <div class="form-tip">最多可上传9张图片，支持jpg、png、gif格式</div>
              </a-form-item>
            </a-form>
          </a-card>
        </a-col>

        <!-- 右侧预览区域 -->
        <a-col :span="10">
          <a-affix :offset-top="20">
            <a-card title="实时预览" :bordered="false">
              <PreviewPhone :preview-data="previewData" />
            </a-card>
          </a-affix>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { SaveOutlined, FileTextOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import type { Dayjs } from 'dayjs'
import dayjs from 'dayjs'
import type {
  Post,
  School,
  SchoolPageParams,
  PostCategory,
  PostCategoryPageParams,
  PostRequest,
} from '@/types'
import { postService } from '@/api/post'
import { schoolService } from '@/api/school'
import { postCategoryService } from '@/api/postCategory'
import { uploadFile } from '@/utils/upload'
import { debounce } from '@/utils/debounce'
import PreviewPhone from './components/PreviewPhone.vue'

// 路由相关
const route = useRoute()
const router = useRouter()

// 判断是否为编辑模式
const isEditing = computed(() => !!route.params.id)

// 页面状态
const submitting = ref(false)
const formRef = ref()
const hasDraft = ref(false)

// 学校和分类数据
const schoolList = ref<School[]>([])
const categoryList = ref<PostCategory[]>([])

// 表单数据
const formData = reactive<PostRequest & { pinExpireTime?: Dayjs | null }>({
  title: '',
  content: '',
  schoolId: undefined,
  categoryId: undefined,
  isAnonymous: 0,
  postStatus: 'published',
  isPinned: 0,
  pinExpireTime: null,
  postTagList: [],
  postImages: [],
})

// 置顶开关状态（用于UI显示）
const formPinnedSwitch = ref(false)

// 上传文件列表
const uploadFileList = ref<any[]>([])

// 预览数据
const previewData = reactive({
  title: '',
  content: '',
  images: [] as string[],
  tags: [] as string[],
  isAnonymous: 0,
  userAvatar: 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png',
  userNickname: '测试用户',
  likeCount: 0,
  viewCount: 0,
  commentCount: 0,
  schoolName: '',
  categoryName: '',
})

// 草稿管理
const DRAFT_KEY = 'post_form_draft'

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入帖子标题', trigger: 'blur' },
    { max: 100, message: '标题不能超过100个字符', trigger: 'blur' },
  ],
  content: [
    { required: true, message: '请输入帖子内容', trigger: 'blur' },
    { max: 2000, message: '内容不能超过2000个字符', trigger: 'blur' },
  ],
  schoolId: [{ required: true, message: '请选择所属学校', trigger: 'change' }],
  categoryId: [{ required: true, message: '请选择帖子分类', trigger: 'change' }],
  postStatus: [{ required: true, message: '请选择帖子状态', trigger: 'change' }],
}

// 禁用过去的日期
const disabledDate = (current: Dayjs) => {
  return current && current < dayjs().endOf('day')
}

// 加载学校列表
const loadSchoolList = async (schoolName = '') => {
  try {
    const params: SchoolPageParams = {
      page: 1,
      pageSize: 50,
      schoolName,
    }
    const result = await schoolService.getSchoolPage(params)
    schoolList.value = result.result
  } catch (error) {
    console.error('获取学校列表失败:', error)
  }
}

// 加载分类列表
const loadCategoryList = async () => {
  try {
    const params: PostCategoryPageParams = {
      page: 1,
      pageSize: 100,
      isEnabled: 1,
    }
    const result = await postCategoryService.getPostCategoryPage(params)
    categoryList.value = result.result
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 防抖搜索学校
const handleSchoolSearch = debounce((value: string) => {
  loadSchoolList(value)
}, 500)

// 置顶开关变化处理
const handlePinnedChange = (checked: boolean) => {
  formData.isPinned = checked ? 1 : 0
  if (!checked) {
    formData.pinExpireTime = null
  }
  updatePreview()
}

// 更新预览数据
const updatePreview = () => {
  previewData.title = formData.title || '帖子标题'
  previewData.content = formData.content || '这里是帖子内容...'
  previewData.isAnonymous = formData.isAnonymous || 0
  previewData.tags = formData.postTagList || []

  // 更新图片
  previewData.images = uploadFileList.value
    .filter((file) => file.status === 'done')
    .map((file) => file.response || file.url)

  // 更新学校和分类名称
  const selectedSchool = schoolList.value.find((s) => s.id === formData.schoolId)
  previewData.schoolName = selectedSchool?.schoolName || ''

  const selectedCategory = categoryList.value.find((c) => c.id === formData.categoryId)
  previewData.categoryName = selectedCategory?.categoryName || ''
}

// 图片上传前处理
const beforeUpload = async (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }

  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    message.error('图片大小不能超过5MB!')
    return false
  }

  try {
    const imageUrl = await uploadFile(file, {
      autoCompress: true,
      quality: 0.8,
      maxWidth: 800,
      maxHeight: 800,
    })

    const fileItem = {
      uid: `upload-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      name: file.name,
      status: 'done',
      url: imageUrl,
      response: imageUrl,
    }

    uploadFileList.value.push(fileItem)
    message.success('图片上传成功')

    // 上传成功后更新预览
    nextTick(() => {
      updatePreview()
    })
  } catch (error) {
    message.error('图片上传失败')
  }

  return false
}

// 移除图片
const onRemove = (file: any) => {
  const index = uploadFileList.value.indexOf(file)
  if (index !== -1) {
    uploadFileList.value.splice(index, 1)
    updatePreview()
  }
}

// 保存草稿
const handleSaveDraft = () => {
  const draftData = {
    ...formData,
    pinExpireTime: formData.pinExpireTime
      ? formData.pinExpireTime.format('YYYY-MM-DD HH:mm:ss')
      : null,
    uploadFileList: uploadFileList.value,
    timestamp: Date.now(),
  }

  localStorage.setItem(DRAFT_KEY, JSON.stringify(draftData))
  message.success('草稿保存成功')
  hasDraft.value = true
}

// 加载草稿
const handleLoadDraft = () => {
  Modal.confirm({
    title: '确认加载草稿',
    content: '加载草稿将覆盖当前表单内容，确定要继续吗？',
    onOk: () => {
      const draft = localStorage.getItem(DRAFT_KEY)
      if (draft) {
        try {
          const draftData = JSON.parse(draft)

          // 恢复表单数据
          Object.assign(formData, {
            ...draftData,
            pinExpireTime: draftData.pinExpireTime ? dayjs(draftData.pinExpireTime) : null,
          })

          // 恢复置顶开关状态
          formPinnedSwitch.value = formData.isPinned === 1

          // 恢复上传文件列表
          uploadFileList.value = draftData.uploadFileList || []

          // 更新预览
          updatePreview()

          message.success('草稿加载成功')
        } catch (error) {
          message.error('草稿格式错误，加载失败')
        }
      }
    },
  })
}

// 表单提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true

    const images = uploadFileList.value
      .filter((file) => file.status === 'done')
      .map((file) => file.response || file.url)

    const submitData: PostRequest = {
      ...formData,
      pinExpireTime: formData.pinExpireTime
        ? formData.pinExpireTime.format('YYYY-MM-DD HH:mm:ss')
        : '',
      postImages: images,
      images: JSON.stringify(images),
    }

    if (isEditing.value) {
      await postService.updatePost(submitData)
      message.success('编辑帖子成功')
    } else {
      await postService.createPost(submitData)
      message.success('新增帖子成功')
    }

    // 清除草稿
    localStorage.removeItem(DRAFT_KEY)

    // 返回列表页
    router.push('/circles/post')
  } catch (error) {
    console.error('保存帖子失败:', error)
    message.error('保存帖子失败')
  } finally {
    submitting.value = false
  }
}

// 取消操作
const handleCancel = () => {
  Modal.confirm({
    title: '确认取消',
    content: '取消后将丢失当前编辑内容，确定要退出吗？',
    onOk: () => {
      router.push('/circles/post')
    },
  })
}

// 返回操作
const handleBack = () => {
  handleCancel()
}

// 检查是否有草稿
const checkDraft = () => {
  const draft = localStorage.getItem(DRAFT_KEY)
  hasDraft.value = !!draft
}

// 页面初始化
const initPage = async () => {
  await loadSchoolList()
  await loadCategoryList()

  if (isEditing.value) {
    // 编辑模式：加载帖子数据
    try {
      const postId = Number(route.params.id)
      const postDetail = await postService.getPostDetail(postId)

      Object.assign(formData, {
        ...postDetail,
        pinExpireTime: postDetail.pinExpireTime ? dayjs(postDetail.pinExpireTime) : null,
      })

      formPinnedSwitch.value = formData.isPinned === 1

      // 设置上传文件列表
      uploadFileList.value = (postDetail.postImages || []).map((url, index) => ({
        uid: `-${index}`,
        name: `image-${index}.jpg`,
        status: 'done',
        url: url,
        response: url,
      }))
    } catch (error) {
      message.error('获取帖子详情失败')
      router.push('/circles/post')
      return
    }
  } else {
    // 新增模式：检查草稿
    checkDraft()
  }

  // 初始化预览
  updatePreview()
}

onMounted(() => {
  initPage()
})
</script>

<style scoped lang="scss">
.post-form-page {
  .page-content {
    padding: 0 24px 24px;
  }
}

.form-tip {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}

:deep(.ant-upload-select-picture-card) {
  width: 104px;
  height: 104px;
}

:deep(.ant-upload-list-picture-card-container) {
  width: 104px;
  height: 104px;
}

:deep(.ant-page-header) {
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-card) {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}
</style> 